#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:洪卫
 

import os,sys
import serial
import time
import json
from sys import version_info  
from magetool import urltool

def pythonVersion():
    return version_info.major



url = ''
tid = ''

f = open('data.txt','r')
lines = f.readlines()
f.close()

f = open('init.txt','rb')
initdat = f.read()
f.close()
f = open('init.py','wb')
f.write(initdat)
f.close()

import init
#下边所有请求时间单位为秒
dtime = init.dtime     #按下时间
tcount = init.tcount       #点击次数
tdelay = init.tdelay      #点击间隔时间
asktime = init.asktime     #链接请求间隔，

for i,v in enumerate(lines):
    tmpv = v.strip()
    if tmpv[:4] == 'http':
        url = tmpv
    elif len(tmpv) > 10 and len(tmpv) < 50:
        tid = tmpv

serialT = None

def readPort():
    global serialT
    time.sleep(0.003)
    n = serialT.inWaiting()
    # print(n)
    if n > 0:
        pstr = serialT.read(n)
        if pythonVersion() == 2:
            # return pstr
            print('setial read:%s'%(pstr))
        else:
            # return str(pstr)
            print('setial read:%s'%(str(pstr)))


def sendCmd(pcmd):
    global serialT
    back = None
    if pythonVersion() > 2:
        back = serialT.write(pcmd.encode())
    else:
        back = serialT.write(pcmd)
    serialT.flush()
    print('send cmd,:%s,isOk:%s'%(pcmd,str(back)))
    return back

#'@'工作模式字典
# type2Pins = {1:['0','1'],2:['2','3'],3:['4','5'],4:['6','7'],5:['8','9'],6:['a','b'],7:['c','d'],8:['e','f'],9:['g','h'],10:['i','j'],11:['k','l'],12:['m','n'],13:['o','p'],14:['q','r'],15:['s','t'],16:['u','v']}
type2Pins = {1:['<0000>','<FFFF>'],2:['<0000>','<FFFF>']}


def delaylog(n):
    for i in range(n):
        print('after %ds well exit.'%(n-i))

def touchonce(k=1):
    sendCmd(type2Pins[k][0])
    time.sleep(dtime)
    sendCmd(type2Pins[k][1])
    time.sleep(tdelay)

def checkData(dat):
    itmes = dat['data']['template_data']
    for i,v in enumerate(itmes):
        # print(v)
        print(v['contentE1']['variants'][1]['id'],tid,v['buyCount']['limitNumber'])
        if v['contentE1']['variants'][1]['id'] == tid and v['buyCount']['limitNumber'] > 0:
            return True
    return False


def check(purl=url,pid=tid):
    jstr = urltool.getUrl(purl)
    if jstr:
        dat = json.loads(jstr)
        if checkData(dat):
            return True
    return False

def main():
    global serialT,tdelay,tcount
    f = open('config.txt','r')
    jstr = f.read()
    f.close()
    jdic = json.loads(jstr)
    t = serial.Serial(jdic['port'],jdic['btv'],timeout=0.5)
    serialT = t
    time.sleep(2)
    sendCmd('@')
    readPort()

    sendCmd('<FFFF>')

    isRuned = False

    while True:
        time.sleep(asktime)
        if isRuned:
            print('run end')
            return
        else:
            if check():
                for i in range(tcount):
                    touchonce()
                isRuned = True
            
if __name__ == '__main__':
    main()
